<script lang="ts">
export default {
  name: "typeIndex"
}
</script>


<script setup lang="ts">
import {
  listServiceAllTypePages
} from "@/api/service-all-type";
import {Delete, Plus, Refresh, Search} from "@element-plus/icons-vue";
import {ElForm, ElMessage, ElMessageBox, ElTable} from "element-plus";
import {getCurrentInstance, onMounted, reactive, ref, toRefs} from "vue";
import {ServiceType, ServiceTypeQuery} from "@/api/service-type/types";
import { useRouter } from 'vue-router';
import {
  getServiceTypeForm,
  listServiceTypePages,
  serviceTypeAdd,
  serviceTypeDelete,
  serviceTypeUpdate
} from "@/api/service-type";
import {deleteDictItems} from "@/api/system/dict";
const emit = defineEmits(['serviceTypeClick']);

const queryFormRef = ref(ElForm); // 查询表单
const dataFormRef = ref(ElForm); // 服务类型表单
const dataTableRef = ref(ElTable);

const {proxy}: any = getCurrentInstance();

const router = useRouter()

const state = reactive({
  // 遮罩层
  loading: false,
  // 选中数组
  ids: [] as number[],
  // 总条数
  total: 0,
  formData: {
  } as ServiceType,
  serviceTypeList: [] as ServiceType[],
  // 启用禁用下拉项
  enableOptions: [] as OptionType[],
  dialog: {
    visible: false,
  } as DialogType,
  queryParams: {
    pageNum: 1,
    pageSize: 10,
  } as ServiceTypeQuery,
  rules: {
    serviceTypeName: [{ required: true, message: '请输服务类型名称', trigger: 'blur' }],
  },
  serviceAllTypeOptions: [] as OptionType[],
});

let {
  ids,
  loading,
  formData,
  queryParams,
  enableOptions,
  serviceTypeList,
  total,
  dialog,
  serviceAllTypeOptions,
  rules,
} = toRefs(state);
/**
 * 查询
 */
function handleQuery() {
  loading.value = true;
  listServiceTypePages(state.queryParams).then(({ data }) => {
    state.serviceTypeList = data.list;
    state.total = data.total;
    state.loading = false;
  });
}

/**
 * 重置查询
 */
function resetQuery() {
  queryFormRef.value.resetFields();
  handleQuery();
}

function handleSelectionChange(selection: any) {
  state.ids = selection.map((item: any) => item.id);
}

function handleRowClick(row: any) {
  emit('serviceTypeClick', row);
}

function handleAdd() {
  getServiceAllTypeOptions()
  formData.value.id = undefined;
  dialog.value = {
    title: '新增服务类型',
    visible: true,
  };
}

/**
 * 修改
 */
async function handleUpdate(row: any) {
  const serviceTypeId = row.id || state.ids;
  state.dialog = {
    title: '修改服务类型',
    visible: true,
  };
  getServiceAllTypeOptions()
  getServiceTypeForm(serviceTypeId).then((response: any) => {
    state.formData = response.data;
  });
}
async function getServiceAllTypeOptions() {
  listServiceAllTypePages().then((response:any) => {
    state.serviceAllTypeOptions = response.data.map((item:any) =>
       ({
        value:item.id,
        label:item.totalTypeName
      })
    )
  });
}
function handleSubmit() {
  loading.value = true;
  dataFormRef.value.validate((valid: any) => {
    if (valid) {
      if (state.formData.id) {
        serviceTypeUpdate(state.formData).then(() => {
          ElMessage.success('修改成功');
          closeDialog();
          handleQuery();
        });
      } else {
        serviceTypeAdd(state.formData).then(() => {
          ElMessage.success('新增成功');
          closeDialog();
          handleQuery();
        });
      }
    }
  });
}

/**
 * 取消
 */
function closeDialog() {
  dialog.value.visible = false;
  dataFormRef.value.resetFields();
  dataFormRef.value.clearValidate();
}

/**
 *  删除
 */
function handleDelete(row: any) {
  const id = row.id
  ElMessageBox.confirm('确认删除已选中的数据项?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    serviceTypeDelete(id).then(() => {
      ElMessage.success('删除成功');
      handleQuery();
    });
    }).catch(() => ElMessage.info('已取消删除'));
}

function labelMaintain(id: string) {
  console.log(id)
  router.push({
    path: '/service-type/label',
    query: { typeId: id }
  })
}

function listEnableOptions() {
  proxy.$listDictItemsByTypeCode('enable_status').then((response: any) => {
    state.enableOptions = response?.data;
  });
}

onMounted(() => {
  // 初始化服务类型列表数据
  handleQuery();
  // 初始化启用禁用字典
  listEnableOptions();
});
</script>

<template>
  <div class="app-container">
    <div class="search">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item prop="serviceTypeName" label="类型名称">
          <el-input
            v-model="queryParams.serviceTypeName"
            placeholder="请输入服务类型名称进行搜索"
            clearable
            @keyup.enter="handleQuery"
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item prop="serviceTypeCode" label="类型编码">
          <el-input
            v-model="queryParams.serviceTypeCode"
            placeholder="请输入服务类型编码进行搜索"
            clearable
            @keyup.enter="handleQuery"
            style="width: 200px"
          />
        </el-form-item>

        <el-form-item label="状态">
          <el-select
            v-model="queryParams.state"
            placeholder="全部"
            clearable
            style="width: 200px"
          >
            <el-option
              v-for="item in enableOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleQuery"
          >搜索
          </el-button
          >
          <el-button :icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card>
      <template #header>
        <el-button type="success" :icon="Plus" @click="handleAdd">新增</el-button>
            <el-button
              type="danger"
              :icon="Delete"
              :disabled="ids.length === 0"
              @click="handleDelete"
            >删除</el-button>
      </template>

      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="serviceTypeList"
        @selection-change="handleSelectionChange"
        @row-click="handleRowClick"
        highlight-current-row
        border
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="服务类型名称" align="center" prop="serviceTypeName" width="150" />
        <el-table-column label="服务类型编码" align="center" prop="serviceTypeCode" width="160" />
        <el-table-column label="状态"  align="center" prop="state" width="150">
          <template #default="scope">
            <el-tag v-if="scope.row.state === 1" type="success">启用</el-tag>
            <el-tag v-else type="info">禁用</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime"  label="创建时间" align="center" width="160" />
        <el-table-column prop="updateTime" label="修改时间" align="center" width="160" />
        <el-table-column prop="totalTypeName" label="总类型" align="center" width="160" />
        <el-table-column fixed="right" label="操作" align="center" width="220">
          <template #default="scope">
            <el-button
              type="success"
              link
              @click.stop="handleUpdate(scope.row)"
            >
              修改
            </el-button>
            <el-button
              type="danger"
              link
              @click.stop="handleDelete(scope.row)"
            >
              删除
            </el-button>
            <el-button
              type="primary"
              link
              @click.stop="labelMaintain(scope.row.id)"
            >
              标签维护
            </el-button>

          </template>
        </el-table-column>
      </el-table>

      <!-- pagination -->
      <pagination
        v-if="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="handleQuery"
      />
    </el-card>

    <!-- dialog -->
    <el-dialog
      :title="dialog.title"
      v-model="dialog.visible"
      width="600px"
      @close="closeDialog"
    >
      <el-form
        ref="dataFormRef"
        :model="formData"
        :rules="rules"
        label-width="120px"
      >
        <el-form-item label="服务类型名称" prop="serviceTypeName">
          <el-input v-model="formData.serviceTypeName" placeholder="请输入服务类型名称" />
        </el-form-item>
        <el-form-item label="服务总类型" prop="totalTypeId">
          <el-select v-model="formData.totalTypeId"  placeholder="请选择">
            <el-option
              v-for="item in serviceAllTypeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="state">
          <el-radio-group v-model="formData.state">
            <el-radio :label="1">正常</el-radio>
            <el-radio :label="0">停用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>

  </div>

</template>
